/**
 * 
 */
package uit.comstore.model.blo;

import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import uit.comstore.model.entity.Product;
import uit.comstore.utils.HibernateSessionFactory;

/**
 * @author XIII
 *
 */
public class ProductBLO {

	@SuppressWarnings("unchecked")
	public List<Product> list() {
		List<Product> products = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();		
		session.beginTransaction();
		Query query = session.createQuery("from Product where deleted = :value");
		query.setParameter("value", 0);
		products = query.list();
		session.getTransaction().commit();
		return products;
	}
	
	@SuppressWarnings("unchecked")
	public List<Product> inventoryProduct(){
		List<Product> products = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();		
		session.beginTransaction();
		Query query = session.createQuery("from Product where deleted = :value1 and quantity > :value1");
		query.setParameter("value1", 0);
		products = query.list();
		session.getTransaction().commit();
		return products;
	}
	
	public Product getById(Long id){
		Product product = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		product = (Product) session.get(Product.class, id);
		session.getTransaction().commit();
		return product;
	}
	
	public Product add(Product product) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(product);
		session.getTransaction().commit();
		return product;
	}
	
	public Product delete(Long id) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Product product = (Product) session.load(Product.class, id);
		product.setDeleted(1);
		session.getTransaction().commit();
		return product;
	}
	
	public Product edit(Product prod){
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		prod.setLastModified(new Date());
		session.update(prod);
		session.getTransaction().commit();
		return prod;
	}
}
